package cn.stylefeng.roses.kernel.sync.core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.otter.canal.protocol.CanalEntry;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类型转化工具
 *
 * @author fengshuonan
 * @date 2019-01-17-3:08 PM
 */
@Slf4j
public class TypeUtil {

    /**
     * canal查处的变化转化成具体的实体类
     *
     * @author fengshuonan
     * @Date 2019/1/17 3:09 PM
     */
    public static <T> T createModel(List<CanalEntry.Column> columns, Class<T> clazz) {
        try {

            //临时存放解析出来的数据
            Map<String, Object> attrs = new HashMap<>();

            //遍历canal识别到的每一列，都放到map里
            for (CanalEntry.Column column : columns) {
                String mysqlType = column.getMysqlType();
                String name = column.getName();
                String value = column.getValue();

                //处理类型转化
                if (StrUtil.isNotBlank(value)) {
                    if (mysqlType.toLowerCase().contains("int")) {
                        attrs.put(name, Integer.valueOf(value));
                    } else if (mysqlType.toLowerCase().contains("long")) {
                        attrs.put(name, Integer.valueOf(value));
                    } else if (mysqlType.toLowerCase().contains("bigint")) {
                        attrs.put(name, Long.valueOf(value));
                    } else if (mysqlType.toLowerCase().contains("char")) {
                        attrs.put(name, value);
                    } else if (mysqlType.toLowerCase().contains("varchar")) {
                        attrs.put(name, value);
                    } else if (mysqlType.toLowerCase().contains("date")) {
                        attrs.put(name, DateUtil.parseDateTime(value).toJdkDate());
                    } else if (mysqlType.toLowerCase().contains("text")) {
                        attrs.put(name, value);
                    }
                }
            }

            //map转化为实际的对象
            return BeanUtil.mapToBean(attrs, clazz, true);

        } catch (Exception e) {
            log.error("类型转化错误！", e);
            return null;
        }
    }
}
